<html>
	<head>
	<title>房租租赁管理系统 @B.E</title>
	<link rel="stylesheet" href="style.css">
	<link type="text/css" href="css/smoothness/jquery-ui-1.8.11.custom.css" rel="stylesheet" />	
	<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
	<script type="text/javascript" src="js/jquery-ui-1.8.11.custom.min.js"></script>	
	<script type="text/javascript" src="js/jquery.ui.datepicker-zh-CN.js"></script>	
	<?php 
	error_reporting(PHP_INT_MAX);
	include("function.php");
	header("Content-type:text/html;charset=utf-8");
	?>
	
	<script>
	$(document).ready(function(){
		$(".rentRoom").each(function(){
			
			$(this).click(function(){
				window.location.href="index.php?room="+$(this).attr("room")+"&ts="+Date.parse(new Date());
			});
			
			console.log($(this).attr("room"));

			if(roomList[$(this).attr("room")] != null){
				//console.log(roomList[$(this).attr("room")].status);	
				if(roomList[$(this).attr("room")].status=="rented"){
					$(this).addClass("roomRented");
				}else{
					$(this).addClass("roomAvailable");
				}
				
			}else{
				//console.error("room"+$(this).attr("room")+" don't have record in the database");
				$(this).addClass("roomError");
			}
			
			});
	});
	
	</script>
	
	</head>
	
	
	<body>

	
<?php 
	include_once("submit.php");
?>


<div id="houseLayout" align=left >
	<table class="houseLayout">
	 <tr>
	  <td class="houseCell rentRoom" room="12">12</td>
	  <td class="houseCell rentRoom" room="13">13</td>
	  <td class="houseCell rentRoom" room="14">14</td>
	  <td class="houseCell" >&nbsp;</td>
	  <td class="houseCell" >&nbsp;</td>
	 </tr>
	 <tr >
	  <td class="houseCell rentRoom" room="1" >1</td>
	  <td class="houseCell rentRoom" room="2">2</td>
	  <td class="houseCell rentRoom" room="3">3</td>
	  <td class="houseCell yardDoor">院门</td>
	  <td class="houseCell rentRoom" room="9">9</td>
	 </tr>
	 <tr >
	  <td class="houseCell rentRoom" room="15">15</td>
	  <td colspan=3 class="houseCell">院子</td>
	
	  <td class="houseCell rentRoom" room="10">10</td>
	 </tr>
	 <tr >
	  <td class="houseCell rentRoom" room="4">4</td>
	  <td class="houseCell rentRoom" room="5">5</td>
	  <td class="houseCell houseRoom">&nbsp;</td>
	  <td class="houseCell rentRoom" room="6">6</td>
	  <td class="houseCell rentRoom" room="11">11</td>
	 </tr>
	 <tr >
	  <td class="houseCell rentRoom" room="7">7</td>
	  <td class="houseCell rentRoom" room="8">8</td>
	  <td class="houseCell houseRoom">&nbsp;</td>
	  <td class="houseCell houseRoom">&nbsp;</td>
	  <td class="houseCell houseRoom">&nbsp;</td>
	 </tr>
	</table>
</div>


<?php 

$rooms = array();

//echo "hello?";
$result1 =  mysql_query("select no, name, status from room  order by no");
if(!$result1){
	die("error when get rooms: ".mysql_error());
}else{
	
	$jsonStr ="{";
	
	while ($row = mysql_fetch_array($result1)){
		$room = new Room();
		$room->no = $row['no'];
		$room->name = $row['name'];
		$room->status = $row['status'];				
		$rooms[$room->no]=$room;
		$jsonStr=$jsonStr."\"".$row['no']."\":{\"name\":\"".$row['name']."\", \"status\":\"".$row['status']."\"},";
		
	}
	$jsonStr =substr($jsonStr,0,strlen($jsonStr)-1)."}";
}
echo "<script>";
echo "var roomList=".$jsonStr;
echo "</script>";
echo '<div id="roomStatusArea">';
echo '<h3>房间状态</h3>';


echo '</div>';
$roomNo=null;

	if( isset($_GET['room'])){
		$roomNo = 	$_GET['room'];
	}else if(isset($_POST['room'])){
		$roomNo = 	$_POST['room'];
	}else{
		//echo "error: can't decide the room id";
		//TODO: can display some general information here
	}

if(trim($roomNo) != ''){
	
	if($rooms[$roomNo]->status=='available'){
?>
		<p >出租</p>
		
		<form action="index.php" method="post">
		<input type="hidden" name="action" value="checkin"/>
		<table>
			<tr>
				<td class="label"><label  for="room">房间：</label></td>
				<td>
					<?php echo $roomNo?><input type="hidden" name="room" value="<?php echo $roomNo?>">
					<?php if(isset($errors['room'])) echo $errors['room']?>
				</td>
			</tr>
			<tr>	
				<td class="label"><label for='renter'>出租人：</label></td>
				<td>
					<input  type="text" name='renter' <?php if(!empty($errors)){ echo "value='".$_POST["renter"]."'";}?>  id="renter"/>
					<?php if(isset($errors['renter'])) echo $errors['renter']?>
				</td>
			</tr>
			<tr>	
				<td class="label"><label for='idno'>身份证号：</label> </td>
				<td>
					<input type="text" name="idno" <?php if(!empty($errors)){ echo "value='".$_POST["idno"]."'";}?>   id="idno" maxlength="18"/>
				</td>
			</tr>
			<tr>	
				<td class="label"><label for='rental'>租金：</label></td>
				<td>
					<input type='text' name="rental" size="5" <?php if(!empty($errors)){ echo "value='".$_POST["rental"]."'";}?>  id="rental"/>元
					<?php if(isset($errors['rental'])) echo $errors['rental']?>
				</td>
			</tr>
			<tr>	
				<td class="label"><label for='checkinDate'>入住日期：</label></td>
				<td>
					<script>
						$(function() {
							$("#checkinDT").datepicker({ 
								dateFormat: 'yy-mm-dd',
								showAnim: 'blind',
								minDate:new Date(<?php echo date('Y,m-1,d')?>),
								appendText: '(yyyy-mm-dd)',
								//numberOfMonths: 2,
								showOtherMonths: false,
								selectOtherMonths: false,
								defaultDate:+0
								
									 });
							$("#checkinDT").datepicker( "option", $.datepicker.regional['zh-CN']);
							$("#checkinDT").datepicker( "option", "disabled", false );
						});
					</script>
					<input  type="text" id="checkinDT" name="checkinDate" <?php 
					if(!empty($errors)){ echo "value='".$_POST["checkinDate"]."'";}
					else{echo "value='".date('Y-m-d')."'";}
					?>  id="checkinDate"/>
					<?php if(isset($errors["checkinDate"])) echo $errors["checkinDate"]?><br/>
				</td>
			</tr>	
			<tr>
				<td class="label"><label for='electricMeter'>电表度数：</label></td> 
				<td>
					<input type="text" name='electricMeter' size="5" <?php if(!empty($errors)){ echo "value='".$_POST["electricMeter"]."'";}?>   id='electricMeter' />度
					<?php if(isset($errors['electricMeter'])) echo $errors['electricMeter']?><br/>
				</td>
			</tr>
			<tr>	
				<td colspan="2"><input type="submit" value="入住"/></td>
			</tr>
		</table>
		</form>
	
	
	<?php }else if($rooms[$roomNo]->status=='rented'){
		
		$result = mysql_query("select `id`,`room` ,`renter` ,`rental` ,`ele_meter_start` ,`ele_meter_end` ,`idNo`,`check_in` from contract 
		where room = ".$roomNo." order by id desc");
		//echo $result;
		
		$row = mysql_fetch_array($result);
		//var_dump($row);
		?>
		<p >出租中。。。</p>
		<table>
			<tr>
		 		<td class="label"><label for="room">房间：</label></td><td><span><?php echo $row['room']?></span></td>
			</tr>
			<tr>
		 		<td class="label"><label for='renter'>出租人：</label></td><td><span><?php echo $row['renter']?></span></td>
			</tr>
			<tr>
		 		<td class="label"><label for='idno'>身份证号：</label></td><td><span><?php echo $row['idNo']?></span></td>
			</tr>
			<tr>
		 		<td class="label"><label for='rental'>租金：</label></td><td><span><?php echo $row['rental']?> 元/月</span></td>
			</tr>
			<tr>
		 		<td class="label"><label for='checkinDate'>入住日期：</label></td><td><span><?php echo date("Y-m-d",strtotime($row['check_in']))?></span></td>
			</tr>
			<tr>
		 		<td class="label"><label for='electricMeter'>初始电表：</label></td><td><span><?php echo $row['ele_meter_start'] ?> 度</span></td>
			</tr>
			
		</table>
		
		<h4>交房租</h4>
		 <form action="index.php" method="post">
		 	<input type="hidden" name="action" value="payment"/>
		 	<input type="hidden" name="room" value="<?php echo $row['room']?>"/>
		 	<input type="hidden" name="contract" value="<?php echo $row['id']?>"/>
		 	
		 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['room']))  
		 		printErrorMsg($errors['room'])?>
		 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['contract']))  
		 		printErrorMsg($errors['contract'])?>
		 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['from']))  
		 		printErrorMsg( $errors['from'])?>
		 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['to']))  
		 		printErrorMsg( $errors['to'])?>
		 	
			 <table>
				 <tr>
				 	<td class="label"><label for="month">缴费时段：</label></td><td>
				 	<?php 
				 	//Get the latest payment for the current room contract
				 	$result1 = mysql_query("select `to` from `journal` where `room_id`=".$row['room']." and `contract_id`=".$row['id']." order by `id` desc limit 0,1");
				 	$row1 = mysql_fetch_array($result1);
				 	
				 	$start=null;
				 	$end=null;
				 	if($row1){
				 		//Already have the payment, make the payment for next period
				 		$start = new DateTime($row1['to']);
				 		$start->add(new DateInterval('P1D'));
				 		$end = new DateTime($row1['to']);
				 		$end->add(new DateInterval('P1M'));
				 	}else{
				 		//no payment yet get the check_in date as the first date
					 	$start = new DateTime($row['check_in']);
					 	$end = new DateTime($row['check_in']);
					 	$end->add(new DateInterval('P1M'))->sub(new DateInterval('P1D'));
				 	}
				 	
				 	$result2 =  mysql_query("select max(electric_degree) \"electric_degree\" from journal where `room_id`=".$row['room']." 
				 							and `contract_id`=".$row['id']." limit 0,1");
				 	
				 	$row2 = mysql_fetch_array($result2);
				 	echo "<script>";
				 	echo "var maxElectricDegree=".$row2['electric_degree'];
				 	echo "</script>";
				 	?>
				 	<input type="hidden" name="from" value="<?php echo $start->format('Y-m-d')?>"/>
				 	<input type="hidden" name="to" value="<?php echo $end->format('Y-m-d')?>"/>
				 	<?php echo $start->format('Y-m-d').' 到 '.$end->format('Y-m-d');?>
				 	</td>
				 </tr>
				 <tr>
				 	<td class="label"><label for="rentalFee">租金：</label></td>
				 	<td><input type="text" name="rentalFee" 
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& !empty($errors)){ 
				 		echo "value='".$_POST["rentalFee"]."'";}?> /> 元
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['rentalFee'])) 
				 		printErrorMsg($errors['rentalFee'])?>
				 	</td>
				 </tr>
				 <tr>
				 <script>
				 $(document).ready(function(){
					$("#electricDegree").blur(function(){
						var newElectricDegree = $(this).val();
						$("#electricFee").val((newElectricDegree-maxElectricDegree)*0.8);

						});
				 });
				 
				 </script>
				 	<td class="label"><label for="electricDegree">电表度数：</label></td>
				 	<td><input type="text" id="electricDegree" name="electricDegree" 
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& !empty($errors)){ 
				 		echo "value='".$_POST["electricDegree"]."'";}?> /> 度
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['electricDegree']))  
				 		printErrorMsg( $errors['electricDegree'])?>
				 	</td>
				 </tr>
				 <tr>
				 	<td colspan="2">最后一次电费交到: <?php echo $row2['electric_degree']?>度</td>
				 </tr>
				 <tr>
				 	<td class="label"><label for="electricFee">电费：</label></td>
				 	<td><input type="text" id="electricFee" name="electricFee" 
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& !empty($errors)){ 
				 		echo "value='".$_POST["electricFee"]."'";}?>/>元
				 	<?php if(isset($_POST['action']) && 'payment'==$_POST['action']&& isset($errors['electricFee']))  
				 		printErrorMsg( $errors['electricFee'])?>
				 	</td>
				 </tr>
				 <tr>
				 	<td colspan="2"><input type="submit" value="交房租"></td>
				 </tr>
			 </table>
		 </form>
		
		<h4>退房</h4>
		
		 <form action="index.php" method="post">
		 	<input type="hidden" name="action" value="checkout"/>
		 	<input type="hidden" name="room" value="<?php echo $row['room']?>"/>
		 	<input type="hidden" name="contract" value="<?php echo $row['id']?>"/>
			<table>
			 <tr>
			 <?php 
			 	if($row1){
			 		$lastPayment = new DateTime($row1['to']);
			 	}else{
			 		$lastPayment = new DateTime($row['check_in']);
			 	}
			 	$checkoutDay = new DateTime();
			 	$days = $lastPayment->diff($checkoutDay)->days;
			 	
			 	if($lastPayment > $checkoutDay){
			 		$days = -$days;
			 	}
			 	
			 	 $finalAmount = $row['rental']/30*$days;
			 	?>
			 	<td class="label">
			 	<?php if($finalAmount>0)
			 	echo '还需支付房租：';
			 	else echo '退还房租：';
			 	?>
			 	
			 	</td><td><?php echo number_format($finalAmount,2)?>
			 	
			 	<input type="hidden" name="checkoutDate" value="<?php echo $checkoutDay->format('Y-m-d');?>"/>
			 	<input type="hidden" name="balancedAmount" value="<?php echo $finalAmount;?>"/>
			 	</td>
			 </tr>
			 <tr>
			 <script>

				var balancedAmt = <?php echo $finalAmount;?>;
			 
			 $(document).ready(function(){
					$("#electricDegree2").blur(function(){
						var newElectricDegree = $(this).val();
						if(newElectricDegree>0){
						var needPayForElec=(newElectricDegree-maxElectricDegree)*0.8;
							$("#electricFee2").val(needPayForElec);
							$("#finalAmount").text(balancedAmt+needPayForElec);
						}
						});
				 });
			 </script>
			 	<td class="label"><label for="electricDegree">电表度数：</label></td>
			 	<td><input type="text" id="electricDegree2" name="electricDegree" <?php 
			 	if(isset($_POST['action']) && 'checkout'==$_POST['action']&& !empty($errors)){ 
			 		echo "value='".$_POST["electricDegree"]."'";}?> />
			 	<?php if(isset($_POST['action']) && 'checkout'==$_POST['action']&& isset($errors['electricDegree']))  
			 		printErrorMsg( $errors['electricDegree'])?>
			 	</td>
			 </tr> 
			 <tr>
			 	<td colspan="2">最后一次电费交到: <?php echo $row2['electric_degree']?>度</td>
			 </tr>
			 <tr>
			 	<td class="label"><label for="electricFee">电费：</label></td>
			 	<td><input type="text" id="electricFee2" name="electricFee" <?php 
			 	if(isset($_POST['action']) && 'checkout'==$_POST['action']&& !empty($errors)){ 
			 		echo "value='".$_POST["electricFee"]."'";}?>/>
			 	<?php if(isset($_POST['action']) && 'checkout'==$_POST['action']&& isset($errors['electricFee']))  
			 		printErrorMsg( $errors['electricFee'])?>
			 	</td>
			 </tr>
			 <tr>
			 	<td>还需支付(房租+电费)</td><td ><span id="finalAmount"></span>元</td>
			 </tr>
			</table>
			<input type="submit" value="退房">
		</form>
		<?php 
	}
	
}else{
	$result4 = mysql_query("SELECT `room_id`, (`contract_id`), max(`to`) \"to\",DATEDIFF(`to`,date(NOW())) \"diff\" FROM `journal`
 	where contract_id in (select max(`contract_id`) from journal group by room_id) and DATEDIFF(`to`,date(NOW())) <=3
  group by `room_id`,`contract_id` ");
	
	while($row4 = mysql_fetch_array($result4)){
		
		$diff = $row4["diff"];
		if($diff >0){
			echo "<a href='index.php?room=".$row4["room_id"]."&ts=".time()."'>房间".$row4["room_id"]."</a>即将要交房租，交租日期".$row4["to"]."</br>";
		}else if($diff<0){
			echo "<a href='index.php?room=".$row4["room_id"]."&ts=".time()."'>房间".$row4["room_id"]."</a>已经过了交租时间".$diff."天</br>";
		}
	}
}

?>

	</body>
</html>
